package com.bijava.producer;

import cn.hutool.core.util.IdUtil;
import com.bijava.entity.OrderEvent;
import com.lmax.disruptor.RingBuffer;

import java.util.UUID;

/**
 * @author swifty
 * @version 1.0.0
 * @since 2024-12-30
 */
public class OrderEventProducer {
    private final RingBuffer<OrderEvent> ringBuffer;

    public OrderEventProducer(RingBuffer<OrderEvent> ringBuffer) {
        this.ringBuffer = ringBuffer;
    }

    public void onData(String userId, double price) {
        long sequence = ringBuffer.next();  // 获取下一个序列号
        int bufferSize = ringBuffer.getBufferSize();
        try {
            System.out.println("============bufferSize：" + bufferSize + "，sequence：" + sequence);
            OrderEvent orderEvent = ringBuffer.get(sequence); // 获取事件对象
            orderEvent.setOrderId(IdUtil.nanoId());
            orderEvent.setUserId(userId);
            orderEvent.setPrice(price);
            orderEvent.setStatus("未支付");
        } finally {
            ringBuffer.publish(sequence);  // 发布事件
        }
    }
}
